import socket
import os
import threading

def handle_thread_request(new_socket):
    recv_data = new_socket.recv(1024 * 4)
    # 判断阴关闭浏览器传过来空值处理
    if len(recv_data) == 0:
        print("关闭浏览器了")
        new_socket.close()
        return
    recv_content = recv_data.decode("utf-8")
    # 最大切割2个，获取路径
    request_path = recv_content.split(" ", 2)[1]
    # 判断访问无路径情况
    if request_path == "/":
        request_path = "/index.html"
    print(request_path)

    try:
        # 打开文件，读取数据
        with open("static" + request_path, 'rb') as f:
            file_data = f.read()
    except Exception as e:
        # 响应行
        response_line = "HTTP/1.1 404 Not Found\r\n"
        # 响应头
        response_header = "server: PWS/1.0\r\n"
        with open("static/error.html", "rb") as f:
            file_data = f.read()
        # 空行
        response_empth_line = "\r\n"
        # 响应体
        response_body = file_data
        response_data = ((response_line +
                          response_header +
                          response_empth_line).encode("utf-8") +
                         response_body)
        # 发送相应数据
        new_socket.send(response_data)
    else:
        # 响应行
        response_line = "HTTP/1.1 200 OK\r\n"
        # 响应头
        response_header = "server: PWS/1.0\r\n"
        # 空行
        response_empth_line = "\r\n"
        # 响应体
        response_body = file_data
        # 因读取模式是rb，读取二进制数据，需要将字符串编码
        response_data = ((response_line +
                          response_header +
                          response_empth_line).encode("utf-8") +
                         response_body)

        # 发送相应数据
        new_socket.send(response_data)
    finally:
        # 关闭套接字
        new_socket.close()


def main():
    # 创建套接字
    tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # 绑定端口号
    tcp_server.bind(("", 8000))
    # 设置监听
    tcp_server.listen(128)
    # 循环等待请求
    while True:
        # 等待客户端请求
        new_socket, ip_port = tcp_server.accept()
        sub_thread = threading.Thread(target=handle_thread_request, args=(new_socket,))
        sub_thread.daemon = True
        sub_thread.start()

if __name__ == '__main__':
    main()